import 'package:flutter/material.dart';
import 'package:flutter_app/api/api.dart' as api;
import 'package:flutter_app/bean/respon.dart';
import 'package:flutter_app/ui/pages/content.dart';

class CategoryInfoListPage extends StatefulWidget {
  final int cid;
  final String title;

  CategoryInfoListPage(this.cid, this.title);

  @override
  CategoryInfoListPageState createState() {
    return new CategoryInfoListPageState(cid, title);
  }
}

class CategoryInfoListPageState extends State<CategoryInfoListPage> {
  List<dynamic> _data;
  int _page = 0;
  int _cid = 294;
  String _title;

  CategoryInfoListPageState(this._cid, this._title);

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
    api.clearOb();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(_title),
        ),
        body: _getBody());
  }

  Widget _getBody() {
    return new NotificationListener(
      child: new ListView.builder(
          itemCount: _data == null ? 0 : _data.length,
          itemBuilder: _getListItem),
      onNotification: (OverscrollIndicatorNotification on) {
        print(on.leading);
        if (on.leading) {
          _page = 0;
          api.getCategoryInfoList(_onDataLoad, _page, _cid);
        } else {
          api.getCategoryInfoList(_onDataLoad, ++_page, _cid);
        }
      },
    );
  }

  Widget _getListItem(BuildContext ctx, int index) {
    return Card(
      child: Container(
          padding: const EdgeInsets.all(8.0),
          child: GestureDetector(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text("项目标题: " + _data[index]['title']),
                Text("创建日期: " + _data[index]['niceDate']),
                Text("项目描述: " + _data[index]['desc']),
              ],
            ),
            onTap: () {
              Navigator.of(context).push(new MaterialPageRoute(builder: (ctx) {
                var info = new OneInfo.fromJson(_data[index]);
                return new ContentPage(info);
              }));
            },
          )),
    );
  }

  void _loadData() {
    api.getCategoryInfoList(_onDataLoad, _page, _cid);
  }

  void _onDataLoad(dynamic data) {
    setState(() {
      if (_page == 0) {
        this._data = data;
      } else if (data.length <= 0) {
        _page--;
      } else {
        this._data.addAll(data);
      }
    });
  }
}
